<?php
namespace app\libs\swoole;

class Client
{
    private $client;

    public function __construct()
    {
        $this->client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
    }

    public function connectBak()
    {
        if (!$this->client->connect('127.0.0.1', 9501, 1)) {
            exit("connect failed. Error: {$this->client->errCode}\n");
        }
        $message = $this->client->recv();
        echo "Get Message From Server:{$message}\n";

        fwrite(STDOUT, '请输入消息：');
        $msg = trim(fgets(STDIN));
        $this->client->send($msg);
    }
    public function connect()
    {
        $this->client->on('connect', function (\swoole_client $cli) {
            fwrite(STDOUT, '请输入消息：');
            $msg = trim(fgets(STDIN));
            $cli->send($msg);
//            $cli->send("GET / HTTP/1.1\r\n\r\n");
        });
        $this->client->on('receive', function (\swoole_client $cli, $data) {
            echo "Receive: $data";
//            $cli->send(str_repeat('A', 5) . "\n");
            sleep(1);
        });
        $this->client->on('error', function (\swoole_client $cli) {
            echo "error\n";
        });
        $this->client->on('close', function (\swoole_client $cli) {
            echo "Connection close\n";
        });
        $this->client->connect('127.0.0.1', 9501);
    }
}
